var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
var cors = require('cors');//跨域
var ejs = require('ejs');//html展示

// var expressJWT = require('express-jwt');
// var {secret} = require('./app_server/utils/config')
// var {requestVerify} = require('./app_server/middleware/verify')

// var genNum = 1

//路由声明
var indexRouter = require('./app_server/routes/index');
var usersRouter = require('./app_server/routes/users')
var loginRouter = require('./app_server/routes/login');
var apiRouter = require('./app_server/routes/api');


var app = express();

// view engine setup 设置页面渲染
app.set('views', path.join(__dirname,'app_server','views'));
// app.set('view engine', 'jade');
app.engine('html', ejs.renderFile)
app.set('view engine','html')

//配置中间件
app.use(logger('dev'));
app.use(cors());
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
// app.use(express.static(path.join(__dirname, 'node_modules')))
// app.use(numGen)
//路由拦截  有点问题，改用jwt的拦截
// app.use(
//   expressJWT({ secret: secret, algorithms: ['HS256'] }).unless({
//     path: [/^\/login/, /^\/api/],
//   }),(req,res,next)=>{ next()}
// )

//配置路由
app.use('/', indexRouter)
app.use('/login', loginRouter);
// -------
app.use('/users', usersRouter)
app.use('/api',apiRouter);

// catch 404 and forward to error handler 捕获404
app.use(function(req, res, next) {
  next(createError(404));
});

// error handler 配置错误中间件
app.use(function(err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};
  
  if (err.name === 'UnauthorizedError') {
    // return res.status(401).send('invalid token...')
    return res.redirect('/login')
  }

  // render the error page
  res.status(err.status || 500);
  res.render('error')
});

module.exports = app;